package com.bxs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bxs.global.JsonResult;
import com.bxs.mapper.FilterRuleMapper;
import com.bxs.mapper.RuleMapper;
import com.bxs.pojo.BaseRule;
import com.bxs.pojo.FilterRule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 抓包过滤规则管理
 */
@RestController
public class DetectRuleController {
    @Autowired
    RuleMapper ruleMapper;

    @GetMapping("detectRuleList")
    public JsonResult filterRuleList(@RequestParam Map<String, Object> param){
        QueryWrapper<BaseRule> queryWrapper = new QueryWrapper<>();
        List<BaseRule> rules = ruleMapper.selectList(queryWrapper);
        return JsonResult.success(rules);
    }

    @PostMapping("detectRuleAdd")
    public JsonResult filterRuleAdd(@RequestBody Map<String, Object> param) throws JsonProcessingException {
        System.out.println("add: " + param);
        param = (Map)param.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(param);
        BaseRule data = objectMapper.readValue(s, BaseRule.class);
        ruleMapper.insert(data);
        return JsonResult.success(data);
    }

    @GetMapping("detectRuleDelete")
    public JsonResult filterRuleDelete(@RequestParam Map<String, Object> param){
        Integer id = Integer.valueOf((String)param.get("id"));
        int i = ruleMapper.deleteById(id);
        return JsonResult.success(i);
    }

    @PostMapping("detectRuleUpdate")
    public JsonResult filterRuleUpdate(@RequestBody Map<String, Object> param) throws JsonProcessingException {
        param = (Map)param.get("data");
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(param);
        BaseRule data = objectMapper.readValue(s, BaseRule.class);
        int i = ruleMapper.updateById(data);
        return JsonResult.success(i);
    }
}
